<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialog()">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" border stripe row-key="id">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,index1) in scope.row.childs"
              :key="item1.id"
              :class="['bdbottom', index1 === 0 ? 'bdtop':'' , 'vcenter']"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightsById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <!-- for循环嵌套渲染出二级权限 -->
                <el-row
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 === 0 ? '':'bdtop' ,'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightsById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightsById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRolesDialog(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRolesById(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框区域 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogVisible"
      width="50%"
      @close="addRolesDialogClose()"
    >
      <!-- 主体内容区域 -->
      <el-form :model="addRolesForm" :rules="RolesRules" ref="addRolesRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 脚部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框区域 -->
    <el-dialog
      title="修改信息"
      :visible.sync="editRolesDialogVisible"
      width="50%"
      @close="editRolesDialogClose()"
    >
      <!-- 主体内容区域 -->
      <el-form :model="editRolesForm" :rules="RolesRules" ref="editRolesRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 脚部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框区域 -->
    <el-dialog
      title="设置权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose()"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色数据
      rolesList: [],
      // 控制添加角色对话框的显示
      addRolesDialogVisible: false,
      // 添加添加角色的数据
      addRolesForm: { roleName: '', roleDesc: '' },
      // 添加与修改角色的规则
      RolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 控制编辑角色面板的显示
      editRolesDialogVisible: false,
      // 编辑角色的数据
      editRolesForm: { id: '', roleName: '', roleDesc: '' },
      // 控制分配权限对话框的显示
      setRightDialogVisible: false,
      // 所有权限列表数据
      rightsList: [],
      // 树形控件绑定的属性
      treeProps: { label: 'authName', children: 'children' },
      // 默认选中的节点
      defKeys: [],
      // 即将分配权限的角色id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get('/v1/roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
      this.rolesList.forEach(item => {
        item.childs = item.children
        delete item.children
      })
      console.log(this.rolesList)
    },
    // 显示添加角色对话框
    addRolesDialog() {
      this.addRolesDialogVisible = true
    },
    // 添加角色对话框关闭的监听事件 清除数据
    addRolesDialogClose() {
      this.$refs.addRolesRef.resetFields()
    },
    // 预校验并添加角色
    addRoles() {
      this.$refs.addRolesRef.validate(async value => {
        if (!value) return
        // 通过预验证 可以发起网络请求
        const { data: res } = await this.$http.post(
          '/v1/roles',
          this.addRolesForm
        )
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败！')
        }
        // 刷新数据
        this.getRolesList()
        // 关闭面板
        this.addRolesDialogVisible = false
        // 提示添加成功
        this.$message.success('添加角色成功！')
      })
    },
    // 显示编辑对话框
    editRolesDialog(row) {
      console.log(row)
      this.editRolesForm.id = row.id
      this.editRolesForm.roleName = row.roleName
      this.editRolesForm.roleDesc = row.roleDesc
      this.editRolesDialogVisible = true
    },
    // 编辑角色对话框关闭的监听事件 清除数据
    editRolesDialogClose() {
      this.$refs.editRolesRef.resetFields()
    },
    // 预校验并修改角色
    editRoles() {
      this.$refs.editRolesRef.validate(async value => {
        if (!value) return
        // 通过预验证 可以发起网络请求
        const { data: res } = await this.$http.put(
          '/v1/roles/' + this.editRolesForm.id,
          {
            roleName: this.editRolesForm.roleName,
            roleDesc: this.editRolesForm.roleDesc
          }
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改信息失败！')
        }
        // 刷新数据
        this.getRolesList()
        // 关闭面板
        this.editRolesDialogVisible = false
        // 提示添加成功
        this.$message.success('修改信息成功！')
      })
    },
    // 根据id删除角色
    async removeRolesById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('/v1/roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }
      this.getRolesList()
      this.$message.success('删除成功！')
    },
    // 根据id删除权限
    async removeRightsById(role, rightsId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 发起网络请求
      const { data: res } = await this.$http.delete(
        `/v1/roles/${role.id}/rights/${rightsId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      console.log(role)
      role.childs = res.data
      console.log(res.data)
      this.$message.success('删除成功！')
    },
    // 显示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限列表
      const { data: res } = await this.$http.get('/v1/rights/tree')
      console.log(res.data)
      this.rightsList = res.data
      this.setRightDialogVisible = true
      // 获取该角色拥有的权限
      role.childs.forEach(item1 => {
        item1.children.forEach(item2 => {
          item2.children.forEach(item3 => {
            this.defKeys.push(item3.id)
          })
        })
      })
    },
    // 监听分配权限的对话框关闭事件
    setRightDialogClose() {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const {
        data: res
      } = await this.$http.post(`/v1/roles/${this.roleId}/rights`, {
        rids: idStr
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.setRightDialogVisible = false
      this.getRolesList()
      this.$message.success('分配权限成功！')
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eeeeee;
}

.bdbottom {
  border-bottom: 1px solid #eeeeee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
